<?php


namespace App\Helpers;


use App\Exceptions\CustomException;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Modules\Car\Entities\CarOrder;


trait Wallet
{
    /**
     *
     * @param $diamond
     * @param $wall_id
     * @throws CustomException
     */
    public function WalletCoinUpdate($diamond,$wall_id){
        if($diamond<0){
            throw new CustomException('金币运算结果有误,请联系管理员!');
        }
        $is_line = DB::update('update user_wallets set diamond = diamond -  ? where id = ? and diamond >= ?', [$diamond,$wall_id,$diamond]);
        if($is_line==0){
            throw new CustomException('余额不足,请及时充值');
        }
    }
    /**
     * 钱包更新
     */
    public function WalletUpdate($diamond,$wall_id){
        if($diamond<0){
            throw new CustomException('运算结果有误,请联系管理员!',201);
        }
        $is_line = DB::update('update user_wallets set diamond =diamond -  ? where id = ? and diamond >= ?', [$diamond,$wall_id,$diamond]);
        if($is_line==0){
            throw new CustomException('余额不足,请及时充值',201);
        }
    }
    //充值钱包
    public function ChangeOrderStatus($trade_no,$order_sn){
        $is_line = DB::update('update user_orders set status = ?,trade_no = ? where order_sn = ? and status = ?', [1,$trade_no,$order_sn,0]);
        if($is_line==0){
            return false;
        }else{
            return true;
        }
    }

    public function incrDiamond($diamond,$wall_id){
      DB::update('update user_wallets set diamond =diamond + ?,diamond_total = diamond_total + ? where id = ? '
        , [$diamond,$diamond,$wall_id]);
    }
    //根据uid增加钱包
    public function incrUidDiamond($diamond,$uid){
        DB::update('update user_wallets set diamond =diamond + ?,diamond_total = diamond_total + ? where uid = ? '
            , [$diamond,$diamond,$uid]);
    }

    public function saveOrUpdateDiamond($uid,$diamond){
      DB::insert (
        'INSERT INTO `user_wallets`( `uid`, `coin`, `coin_total`, `diamond`, `diamond_total`, `created_at`, `updated_at`)'.
        ' VALUES ( ?, 0.00, 0.00, ?, ?, NOW(),NOW()) '.
        ' ON DUPLICATE KEY UPDATE diamond = diamond + ?,'.
        ' diamond_total = diamond_total + ?,'.
        ' updated_at = NOW() '
        , [$uid,$diamond,$diamond,$diamond,$diamond]);
    }
  /**
   * 修改金币数量
   * @param $coin
   * @param $wall_id
   * @throws CustomException
   */
  public function decmentCoin($coin,$wall_id){
        if($coin<0){
            throw new CustomException('运算结果有误,请联系管理员!',201);
        }
        $is_line = DB::update('update user_wallets set coin =coin -  ? where id = ? and coin >= ?', [$coin,$wall_id,$coin]);
        if($is_line==0){
            throw new CustomException('余额不足',201);
        }
    }
    //pcc 操作

    /**
     * @param $table
     * @param $num
     * @param $id
     * 数据库的引擎为 innoDB
     * 操作位于事务块中（BEGIN/COMMIT）
     */
    public function pcc($table,$num,$im_id){
        $data = DB::update('update '.$table.' set diamond = diamond - ? WHERE uid = ? and diamond >= ?', [$num,$im_id,$num]);
        return $data;//0 or 1
    }

    /**
     * occ
     * @param $table
     * @param $num
     * @param $id
     * @param $version 版本号
     */
    public function occ($table,$num,$id){
        $data = DB::select('select * from '.$table.' where uid=?',[$id]);
        $result = DB::update('update '.$table. ' set diamond = diamond - ?,version = version+1 WHERE uid = ? and diamond >= ? and version = ?',[$num,$id,$num,$data[0]->diamond_total]);
        return $result;
    }

    /**
     * 分布式 redis
     */
    public function redis(){
        $expire = 10;//有效期10秒
        $key = 'lock';//key
        $value = time() + $expire;//锁的值 = Unix时间戳 + 锁的有效期
        $lock = Redis::setnx($key, $value);
        //判断是否上锁成功，成功则执行下步操作
        if(!empty($lock))
        {
            return 1;
            //下单逻辑...
        }else{
            return 2;
        }
    }

    /**
     * 插入 忽略操作
     * @param $table
     * @param $diamond
     * @param $id
     * @return bool
     */
    public function insertIgnore($table,$diamond,$im_id){
        $data = DB::insert('INSERT IGNORE INTO '.$table.' (uid,diamond,diamond_total,created_at) VALUES (?,?,?,?)',[$im_id,$diamond,$diamond,now()]);
        return $data;//true
    }

    /**
     * 插入 替换操作
     * @param $table
     * @param $diamond
     * @param $id
     */
    public function replaceInto($table,$diamond,$id){
        $data = DB::insert('replace into '.$table.' (uid,diamond,diamond_total,created_at) VALUES (?,?,?,?)', [$id,$diamond,$diamond,now()]);
        return $data;//true
    }

    /**
     * 插入或更新
     * @param $table
     * @param $diamond
     * @param $id
     * @return bool
     */
    public function insertOrUpdate($table,$diamond,$id){
        $data = DB::insert('insert into '.$table.' (uid,diamond,diamond_total,created_at) values(?,?,?,?) on duplicate key update uid=?,diamond=?,diamond=?,created_at=?',
            [$id,$diamond,$diamond,now(),$id,$diamond,$diamond,now()]);
        return $data;
    }
    //获取订单
    protected function getOrder($order_sn){
            return CarOrder::query()
                ->where('order_sn',$order_sn)
                ->where('status',0)
                ->first();
    }
    //获取记录数据
    protected function recordData($order,$quantity){
        return [
            'uid'=>$order->uid,
            'contents'=>'购买钻石',
            'type'=>1,
            'quantity'=>$quantity,
            'price'=>$order->fee,
            'tag'=>3,
            'diamondable_type'=>'Modules\User\Entities\UserOrder',
            'diamondable_id'=>$order->id,

        ];
    }

}
